﻿
/*
    Microformats human-machine-date 0.1
    Author: Glenn Jones
    
	The MIT License
	
	Copyright (c) 2008 Glenn Jones
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
		
*/




function HumanMachineDate() {
	this.dY;
	this.dM=-1; 
	this.dD=-1;
	this.z=false;
	this.tH;
	this.tM=-1;
	this.tS=-1;
	this.tD=-1;
	this.tzH;
	this.tzM=-1;
	this.tzPN='+';
	this.z = false;

	this.languageDesciptions = new Array(5);
	this.languageDesciptions[0] = {"language-name" : "English", "language-codes" : ["en"], "pattern": "date,month,year,time,timezone", "scrub-terms": ["Date:","at", ",", "Time zone"], "month-names": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]}
	this.languageDesciptions[1] = {"language-name" : "Spanish", "language-codes" : ["es"], "pattern": "date,month,year,time,timezone",  "scrub-terms": ["Fecha:","a las", ",", "Zona horaria"], "month-names": ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]}
	this.languageDesciptions[2] = {"language-name" : "German", "language-codes" : ["de"], "pattern": "date,month,year,time,timezone",  "scrub-terms": ["Datum:","um", ",", "Zeitzone"], "month-names": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]}
	this.languageDesciptions[3] = {"language-name" : "French", "language-codes" : ["fr"], "pattern": "date,month,year,time,timezone", "scrub-terms": ["Date:","d\u00E9calage horaire", ",", "\u00E0"], "month-names": ["janvier", "f\u00E9Avrier", "mars", "avril", "mai", "juin", "juillet", "ao\u016Dt", "septembre", "novembre", "d\u00E9Acembre"]}
	this.languageDesciptions[4] = {"language-name" : "Simplified Chinese", "language-codes" : ["zh","zh-cn","zh-sg"],"pattern": "year,month,date,time,timezone",  "scrub-terms": ["\u65e5\u671f:", "\u5e74", "\u6708", ",", "\u65e5", "\u6642\u5340"], "month-names": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]}

	
	
	if(arguments[1])
		this.Parse( arguments[0],arguments[1] );
}

HumanMachineDate.prototype.Parse = function( dateString, languageCode ) {
	var currentLanguageDesciption = '';
	
	
	
	for (i=0; i <= this.languageDesciptions.length-1; i++)
	{
		for (x=0; x <= this.languageDesciptions[i]['language-codes'].length-1; x++)
		{
			if( this.languageDesciptions[i]['language-codes'][x].toLowerCase() == languageCode.toLowerCase() )
				currentLanguageDesciption = this.languageDesciptions[i];
		}
	}
	if( currentLanguageDesciption != '')
	{
		
		var pattern = currentLanguageDesciption['pattern'];
		var scrubTerms = currentLanguageDesciption['scrub-terms'];
		var parts = '';

		dateString = dateString.toLowerCase();
		alert( dateString );
		
		for (i=0; i <= scrubTerms.length-1; i++){
			// romove terms where they have white space
			dateString = this.scrub( " " + scrubTerms[i].toLowerCase() + " ", dateString );
			dateString = this.scrub( " " + scrubTerms[i].toLowerCase(), dateString );
			dateString = this.scrub( scrubTerms[i].toLowerCase() + " ", dateString );
			
		}
		parts = Trim(dateString,' ').split(' ');
		patternParts = pattern.split(',');
		
		alert( dateString );
		
		var date = Trim(this.getPatternValue('date',patternParts,parts), ' ');
		var month = Trim(this.getPatternValue('month',patternParts,parts), ' ');
		var year = Trim(this.getPatternValue('year',patternParts,parts), ' ');
		var time = Trim(this.getPatternValue('time',patternParts,parts), ' ');
		var timeZone = Trim(this.getPatternValue('timezone',patternParts,parts), ' ');
		
		// Date
		if( date != '' )
			this.dD = this.toTwoDigits(date,true);
			
		for (i=0; i <= currentLanguageDesciption['month-names'].length-1; i++)
		{
			if(currentLanguageDesciption['month-names'][i].toLowerCase() == month.toLowerCase())
				this.dM = this.toTwoDigits(i+1,true);
		}

		if( year != '' )
			this.dY = this.toTwoDigits(year,true);

		// Time
		if( time != '' ){
			// Parse time
			childParts = time.split(':');
			if( childParts[0] ) this.tH = this.toTwoDigits(childParts[0],true);
			if( childParts[1] ) this.tM = this.toTwoDigits(childParts[1],true);
			if( childParts[2] ) this.tS = this.toTwoDigits(childParts[2],true);
		}
		
		// Timezone
		if( timeZone != '' )
		{
			// Parse time zone
			if( timeZone.indexOf('+') > 0 )
				this.tzPN = '+';
				
			if( timeZone.indexOf('-') > 0 )
				this.tzPN = '-';
			
			timeZone = timeZone.replace('+','').replace('-','');
			childParts = timeZone.split(':');
			if( childParts[0] ) this.tzH = this.toTwoDigits(childParts[0],true);
			if( childParts[1] ) this.tzM = this.toTwoDigits(childParts[1],true);
		}
				
	}
}

HumanMachineDate.prototype.scrub = function( test, string ) {
	var output = string;
	if( output.indexOf(test) > -1 ){
		output = output.replace(test, " ");
		output = this.scrub( test, output ); 
	}
	return output;
}

HumanMachineDate.prototype.getPatternValue = function( name, patternParts, parts ) {
	output = '';
	for (i=0; i <= patternParts.length-1; i++){
		if(Trim(patternParts[i].toLowerCase(),' ') == name){
			if(i <= parts.length){
				output = parts[i];
			}
		}
	}
	return output;
}


HumanMachineDate.prototype.toTwoDigits = function( value, atFront ) {
	var output= new String(value);
	if( output.length == 1 )
	{
		if(atFront)
			output = "0" + output;
		else
			output = output + "0";	
	
	}
	return output;
}

HumanMachineDate.prototype.toString = function() {	
	
	dsep = '-';
	tsep = ':';
	
	var output='';
	if( typeof( this.dY ) != 'undefined' && this.dM > 0 && this.dD > 0 ){			
		output = this.dY;
		if( this.dM > 0 && this.dM < 13  ){ 
			output += dsep + this.dM;	
			if(this.dD > 0 && this.dD < 32  ){ 
				output += dsep + this.dD;
				// Time and can only be created with a full date
				if( typeof( this.tH ) != 'undefined' ){
					if( this.tH > -1 && this.tH < 25 ) {
						output += 'T' + this.tH
						if(  this.tM > -1 && this.tM < 61 ) {
							output += tsep + this.tM;
							if(  this.tS > -1 && this.tS < 61 ) {
								output += tsep + this.tS;
								if(  this.tD > -1 )
									output += '.' + this.tD; 
							}
						}
							// Time zone offset can only be created with a hour
							if(this.z) { output += 'Z' };
							if( typeof( this.tzH ) != 'undefined' ){
								if( this.tzH > -1 && this.tzH < 25 ) {
									output += this.tzPN + this.tzH
									if( this.tzM > -1 && this.tzM < 61 ) 
										output += tsep + this.tzM;
								}
							}
					}	
				}	
			}
		}	
	}
	return output;

}



function Trim(str, chars) {
	str = new String(str);
	if(str != "" ){
    	return TrimLeft(TrimRight(str, chars), chars);
    }else{
    	return "";
    }
}

function TrimLeft(str, chars) {
	str = new String(str);
	if(str != ''){
    	chars = chars || "\\s";
    	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }else{
    	return '';
    }
}

function TrimRight(str, chars) {
	str = new String(str);
	if(str != ''){
    	chars = chars || "\\s";
    	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }else{
    	return '';
    }
}





  	


